import React from 'react'
import MUtil from 'util/mm.jsx'
import User from 'service/user-service.jsx'
import './login.css'

const _Ajax=new MUtil()
const _User=new User()

class Login extends React.Component{
  constructor (props) {
    super(props)
    this.state = {
      username: '',
      password: '',
      redirect: _Ajax.getUrlParam('redirect') || '/'
    }
  }
  
  componentWillMount () {
    document.title = '登陆' + 'happy mall'
  }

  inputChange (e) {
    let inputName = e.target.name
    let inputValue = e.target.value
    console.log(inputName, inputValue)
    this.setState({
      [inputName]: inputValue
    })
  }
  //当用户登录的时候
  onSubmit (e) {
    let loginInfo = {
      username: this.state.username,
      password: this.state.password
    }
    let flag = _User.checkLogin(loginInfo)
    if (flag.status) {
      _User.login(loginInfo).then( (res)=>{
        //保存登陆用户名在本地
        _Ajax.setUserInfo('userInfo',res)
        // 登陆成功后跳转到的页面
        this.props.history.push(this.state.redirect)
      }, (err)=>{
        _Ajax.errorTips(err)
      } )

    }else {
       _Ajax.errorTips(flag.msg)
    }
  }

  onKeyUpEvent (e) {
    if(e.keyCode == 13){
      this.onSubmit()
    }
  }

  render () {
    return (
      <div className="panel-login">
        <div className="col-md-4 col-md-offset-4">
          <div className="panel panel-default">
            <div className="panel-heading">欢迎来到happy mall 登陆系统</div>
            <div className="panel-body">
              <div>
                <div className="form-group">
                  <input type="email" name="username" className="form-control" placeholder="请输入用户名" onChange={e=>this.inputChange(e)} onKeyUp={e=> this.onKeyUpEvent(e)} />
                </div>
                <div className="form-group">
                  <input type="password" name="password" className="form-control" placeholder="请输入密码" onChange={e=>this.inputChange(e)} onKeyUp={e=> this.onKeyUpEvent(e)} />
                </div>
                <button className="btn btn-primary btn-block" onClick={e => this.onSubmit(e)}>登陆</button>
              </div>
            </div>
          </div>
        </div>
      </div>
    );
  }
}

export default Login;